package com.rectcircle.db


import com.rectcircle.config.LibraryDbSchema
import com.rectcircle.model.Author
import org.squeryl.PrimitiveTypeMode._

object AuthorDb {

	import com.rectcircle.config.LibraryDbSchema._
	
	
	/**
	 * 
	 * 直接插入
	 * 
	 * @param a
	 * @return
	 */
	def save(a: Author) = authors.insert(a)
	
	def save2(a:Author) = a.save
	
	/**
	 * 更新根据主键
	 * 
	 * @param a
	 */
	def updateById(a: Author) = authors.update(a)
	
	
	/**
	 * 
	 * 条件更新
	 * 
	 * @param newEmail
	 * @return
	 */
	def updateEmailWhereEmail(newEmail:String, oldEmail:String) = update(authors)(
		au⇒where(au.email.get === oldEmail) set(au.email := Some(newEmail))
	)
	
	/**
	 * 
	 * 更新全部
	 * 
	 * @param lastName
	 * @return
	 */
	def updateAllLastName(lastName: String) = update(authors)(
		a ⇒ setAll(a.lastName := lastName)
	)
	
	/**
	 * 批量保存
	 * 
	 * @param as
	 */
	def saveLists(as:Iterable[Author]) = authors.insert(as);
	
	
	
	/**
	 * 根据条件删除
	 * @param a
	 * @return
	 */
	def remove(a:Author) = authors.deleteWhere(oldA ⇒ oldA.id === a.id)
	
	/**
	 * 
	 * 查找根据email
	 * 
	 * @param email
	 * @return
	 */
	def findByEmail(email:String) = from(authors)(
		a⇒ where(a.email.get === email) select (a)
	).single
	
	
	/**
	 * 根据名字查找
	 * @param firstName
	 * @return
	 */
	def findByFirstName(firstName:String) = authors
	.where(_.firstName === firstName)
	
	
	/**
	 * 根据id查询
	 * @param id
	 * @return
	 */
	def getById(id:Long) = authors.lookup(id)
	
	
	//表连接2，查询所有作者的所有书籍
	def findAllAuthorBooksDetail = {
		join(authors, books.leftOuter)((a,b)=>
			//where(a.id === 1)
			select(a,b)
			on(a.id === b.map(_.authorId))
		)
	}
	
	//表连接+groupBy查询，查询该作者有多少本书，不会这么写
	def findBooksCountByAuthorId = {
		join(authors,books)((a,b)=>
			groupBy(a.id)
			compute(count(b.id))
			on(a.id === b.authorId)
		)
	}
	
	def withBook(author: Author) = {
		author.books = LibraryDbSchema.authorToBooks.left(author).toVector
		author
	}

}